/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.sme.services.security;

import java.util.ArrayList;
import java.util.Collection;

import cz.muni.fi.pa165.sme.dao.api.UserDao;
import cz.muni.fi.pa165.sme.dao.entity.User;
import cz.muni.fi.pa165.sme.dao.enumeration.UserRole;
import cz.muni.fi.pa165.sme.dao.exception.DataStorageOperationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author jirankova
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDAO;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user;
        try {
            user = userDAO.getUserByLogin(username);
        } catch (DataStorageOperationException e) {
            user = null;
        }
        if (user != null) {
            String password = user.getPassword();

            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

			if(user.getRole() != null) {
				authorities.add(new SimpleGrantedAuthority(user.getRole().name()));
				if(UserRole.ADMIN.equals(user.getRole())) {
					authorities.add(new SimpleGrantedAuthority(UserRole.USER.name()));
				}
			}

			return new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authorities);
        } else {
            throw new UsernameNotFoundException("User not found!");
        }
    }
}
